<template>
  <div class="app-container">
    <el-row v-if="optType != 'view'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:wm:itemrecpt:edit']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:wm:itemrecpt:edit']"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="itemrecptlineList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="25" align="center" />
      <el-table-column label="物料编码" align="center" width="130px" prop="itemCode" />
      <el-table-column label="物料名称" align="center" width="120px"  prop="itemName"/>
      <el-table-column label="规格型号" align="center" prop="specification" min-width="120">
        <template slot-scope="scope">
          <span :title="scope.row.specification">{{ scope.row.specification || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="订货数量" align="center" prop="quantityOrder" />
      <el-table-column label="入库数量" width="140" align="center" prop="quantityRecived">
        <template slot-scope="scope">
          <el-input-number 
            v-if="optType != 'view' && (!recptId || scope.row.lineId)" 
            v-model="scope.row.quantityRecived" 
            :min="0.01" 
            size="mini"
            @change="handleQuantityChange(scope.row)"
          />
          <span v-else>{{ scope.row.quantityRecived }}</span>
        </template>
      </el-table-column>
      <el-table-column label="批次号" align="center" prop="batchCode">
        <template slot-scope="scope">
          <el-input 
            v-if="optType != 'view' && (!recptId || scope.row.lineId)" 
            v-model="scope.row.batchCode" 
            placeholder="请输入批次号"
            size="mini"
            @change="handleBatchCodeChange(scope.row)"
          />
          <span v-else>{{ scope.row.batchCode || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="warehouseName"  width="130px">
        <template slot-scope="scope">
          <el-cascader 
            v-if="optType != 'view' && (!recptId || scope.row.lineId)"
            v-model="scope.row.warehouseInfo"
            :options="warehouseOptions"
            :props="warehouseProps"
            size="mini"
            @change="(val) => handleWarehouseChanged(val, scope.row)"
            placeholder="请选择仓库/库区/库位"
          />
          <span v-else>{{ scope.row.warehouseName || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库区" align="center" prop="locationName" width="120px" >
        <template slot-scope="scope">
          <span>{{ scope.row.locationName || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库位" align="center" prop="areaName" width="120px" >
        <template slot-scope="scope">
          <span>{{ scope.row.areaName || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="expireDate" width="180px">
        <template slot-scope="scope">
          <el-date-picker 
            v-if="optType != 'view' && (!recptId || scope.row.lineId)"
            v-model="scope.row.expireDate"
            type="date"
            value-format="yyyy-MM-dd"
            size="mini"
            placeholder="选择有效期"
            style="width: 125px"
            @change="handleExpireDateChange(scope.row)"
          />
          <span v-else>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否检验" align="center" width="130" prop="iqcCheck">
        <template slot-scope="scope">
          <el-radio-group 
            v-if="optType != 'view' && (!recptId || scope.row.lineId)"
            v-model="scope.row.iqcCheck" 
            size="mini"
            @change="handleIqcCheckChange(scope.row)"
          >
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
          <dict-tag v-else :options="dict.type.sys_yes_no" :value="scope.row.iqcCheck"/>
        </template>
      </el-table-column>
      <el-table-column label="检验单编号" width="120" align="center" prop="iqcCode">
        <template slot-scope="scope">
          <el-input 
            v-if="optType != 'view' && (!recptId || scope.row.lineId) && scope.row.iqcCheck === 'Y'"
            v-model="scope.row.iqcCode" 
            placeholder="请选择检验单"
            size="mini"
            readonly="readonly"
            @click="handleTableIqcSelect(scope.row)"
          >
            <el-button slot="append" @click="handleTableIqcSelect(scope.row)" icon="el-icon-search"></el-button>
          </el-input>
          <IqcSelect ref="iqcSelect" v-if="showItemSelect" @closeSelect="closeSelect" :title="'选择来料检验单'" @onSelected="onIqcSelected" > </IqcSelect>
          <span v-else-if="scope.row.iqcCheck === 'Y'">{{ scope.row.iqcCode || '' }}</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="130px" v-if="optType != 'view'" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:wm:itemrecpt:edit']"
          >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:wm:itemrecpt:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePaginationChange"
    />
      <ItemSelect ref="itemSelect" v-if="showItemSelect" @closeSelect="closeSelect" @onSelected="onItemSelected" > </ItemSelect>
    <!-- 添加或修改物料入库单行对话框，下面那个用不到了el-dialog -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码"  prop="itemCode">
              <el-input v-model="form.itemCode" readonly="readonly" placeholder="请选择物料编码" >
                <el-button slot="append" @click="handleSelectProduct" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <ItemSelect ref="itemSelect" v-if="showItemSelect" @closeSelect="closeSelect" @onSelected="onItemSelected" > </ItemSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" disabled readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请选择物料编码后自动带出" readonly="readonly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库数量" prop="quantityRecived">
              <el-input-number 
                v-model="form.quantityRecived" 
                :min="0.01" 
                :precision="2"
                placeholder="请输入入库数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入入库批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效期" prop="expireDate">
              <el-date-picker clearable
                v-model="form.expireDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择有效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="warehouseId" required>
              <el-cascader v-model="warehouseInfo"
                :options="warehouseOptions"
                :props="warehouseProps"
                @change="handleWarehouseChanged"
                placeholder="请选择仓库/库区/库位"
              >                  
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否检验">
              <el-radio-group v-model="form.iqcCheck" disabled v-if="optType=='view'">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>

              <el-radio-group v-model="form.iqcCheck" v-else>
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span ="8">
            <el-form-item v-if="form.iqcCheck == 'Y'" label="来料检验单" prop="iqcCode" required>
              <el-input v-model="form.iqcCode" readonly="readonly" placeholder="请选择来料检验单" >
                <el-button slot="append" @click="handleSelectIqc" icon="el-icon-search"></el-button>
              </el-input>
              <IqcSelect ref="iqcSelect" v-if="showItemSelect" @closeSelect="closeSelect" :title="'选择来料检验单'" @onSelected="onIqcSelected" > </IqcSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
             <div slot="footer" class="dialog-footer">
         <el-button type="primary" @click="submitForm">确 定</el-button>
         <el-button @click="cancel">取 消</el-button>
       </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItemrecptline, getItemrecptline, delItemrecptline, addItemrecptline, updateItemrecptline } from "@/api/mes/wm/itemrecptline";
import { delItemrecpt } from "@/api/mes/wm/itemrecpt";
import ItemSelect  from "@/components/itemSelect/multipleChoice.vue";
import IqcSelect from "@/components/iqcSelect/single.vue";

import {getTreeList} from "@/api/mes/wm/warehouse"
import { detailPurchaseOrder } from "@/api/mes/pro/purchaseOrder";
import { getPurchaseOrderMaterials } from "@/api/mes/pro/purchaseOrder";
export default {
  name: "Itemrecptline",
  dicts: ['sys_yes_no'],
  components :{ItemSelect,IqcSelect},
  props:{
    recptId: null,
    optType: null,
    warehouseId: null,
    locationId: null,
    areaId: null,
    poCode: null,
    purchaseOrderData: null, // 新增：接收父组件传递的采购订单数据
    backendData: null, // 新增：接收父组件传递的后端数据
  },
  data() {
    return {
      warehouseInfo:[],
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
        // 允许选择到库位级别
        checkStrictly: false,
        lazy: false,
        expandTrigger: 'hover'
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 物料入库单行表格数据
      itemrecptlineList: [],
      // 所有数据（用于分页）
      allData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recptId: this.recptId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityRecived: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        expireDate: null,
      },
      // 表单参数
      form: {},
      // 当前选中的行数据（用于检验单选择）
      currentRow: null,
      // 是否显示检验单选择弹窗
      showItemSelect: true,
      mergedData: [],
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "产品物料编码不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "产品物料ID不能为空", trigger: "blur" }
        ],
        quantityRecived: [
          { required: true, message: "入库数量不能为空", trigger: "blur" }
        ],
        warehouseId:[
          { required: true, message: "请选择入库仓库", trigger: "change" }
        ],
        batchCode: [
          // 入库批次号不是必填项，允许为空
        ],
        expireDate: [
          // 有效期不是必填项，允许为空
        ],
        iqcCode:[
          { 
            validator: (rule, value, callback) => {
              if (this.form.iqcCheck === 'Y' && !value) {
                callback(new Error('请选择来料检验单'));
              } else {
                callback();
              }
            }, 
            trigger: "blur" 
          }
        ]
      },
    };
  },
  computed: {
    /**
     * 计算数据
     */
    computedMergedData() {
      const localData = this.getFromLocalStorage();
      const backendData = this.backendData || [];
      
      if (!backendData.length && !localData.length) {
        return [];
      }
      
      // 合并数据，避免重复
      const combinedData = [...backendData];
      // 这里是循环的存储的数据
      localData.forEach(localItem => {
        if (!localItem.lineId) {
          const isDuplicate = backendData.some(backendItem => 
            backendItem.itemCode === localItem.itemCode
          );
          
          if (!isDuplicate) {
            combinedData.push(localItem);
          }
        }
      });
      return combinedData;
    }
  },
  created() {
    // 确保分页参数正确初始化
    this.queryParams.recptId = this.recptId;
    // 当前页的页数为第一页
    this.queryParams.pageNum = 1;
    // 当前的数据分页的数量
    this.queryParams.pageSize = 10;
    
    this.getList();
    this.getWarehouseList();
  },
  beforeDestroy() {
  },
  mounted() {
    // 确保检验单组件正确显示
    this.$nextTick(() => {
      if (this.$refs.iqcSelect) {
        console.log('IqcSelect 组件已正确挂载');
      } else {
        console.warn('IqcSelect 组件未找到，可能需要检查组件导入');
      }
    });
  },
  watch: {
    poCode: {
      handler(newVal, oldVal) {
        // 避免重复调用
        if (newVal && newVal !== oldVal) {
          console.log('采购订单号变化，新值:', newVal, '旧值:', oldVal);
          
          // 只有在有新的采购订单号时才清空现有物料列表
          if (newVal && newVal.trim()) {
            // 清空现有物料列表
            this.itemrecptlineList = [];
            this.total = 0;
            // 如果有入库单ID，则获取物料信息
            if (this.recptId) {
              this.getMaterialList();
            } else {
              // 新增模式下，尝试获取物料信息但不强制清空
              this.getMaterialList();
            }
          }
        } else if (!newVal && oldVal) {
          // 只有当从有值变为无值时才清空
          this.itemrecptlineList = [];
          this.total = 0;
        }
        // 如果newVal和oldVal都是null/undefined，不做任何操作
      },
      immediate: false // 改为false，避免初始化时立即执行
    },
    // 监听后端数据变化
    backendData: {
      handler(newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
          // 处理新的后端数据，对其进行一个判断
          this.handleExternalBackendData(newVal, false);
        }
      },
      deep: true
    }
  },
  methods: {
    /** 查询物料入库单行列表 */
    getList() {
      this.loading = true;
      
      // 获取后端传递的数据
      let localData = this.getFromLocalStorage();
      // 调用后端接口获取数据
      listItemrecptline(this.queryParams).then(response => {
        // 这里我是使用了一个常量来接受一个值
        const backendData = response.rows || [];
        if (backendData && backendData.length > 0) {
          // 后端数据
          this.appendBackendData(backendData);
        }else{
          // 如果没有则提示没有任何数据。给用户一些提示信息
          this.renderFromLocalCache();
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取列表失败:', error);
        // 如果后端接口失败，则返回失败的信息
        this.renderFromLocalCache();
        this.loading = false;
      });
    },
        // 根据采购订单获取物料信息
    async getMaterialList() {
      if (!this.poCode) {
        //直接保存，保持原有的数据
        return;
      }
      // 显示加载状态
      this.loading = true;
      try {
        let materialList = [];
        // 方式1：从父组件获取采购订单信息
        if (this.$parent && this.$parent.poCodeOptions) {
          const poInfo = this.$parent.poCodeOptions.find(item => item.poCode === this.poCode);
         // 进行判断
          if (poInfo && poInfo.id) {
            try {
              // 这里是调用接口来去进行赋值
              const poResponse = await detailPurchaseOrder(poInfo.id, {pageNum: 1, pageSize: 999});
              // 检查不同的数据结构
              if (poResponse.rows && poResponse.rows.length > 0) {
                materialList = poResponse.rows;
              } else if (poResponse.data && poResponse.data.purchaseOrderLines && poResponse.data.purchaseOrderLines.length > 0) {
                materialList = poResponse.data.purchaseOrderLines;
                
              } else if (poResponse.data && poResponse.data.materialList && poResponse.data.materialList.length > 0) {
                materialList = poResponse.data.materialList;
                } else {
                console.warn('detailPurchaseOrder接口返回的数据中没有找到物料明细');
                // 尝试从其他可能的字段获取
                if (poResponse.data) {
                  Object.keys(poResponse.data).forEach(key => {
                    if (Array.isArray(poResponse.data[key]) && poResponse.data[key].length > 0) {
                      if (key.toLowerCase().includes('line') || key.toLowerCase().includes('material') || key.toLowerCase().includes('item')) {
                        materialList = poResponse.data[key];
                        }
                    }
                  });
                }
              }
            } catch (apiError) {
              console.error('调用detailPurchaseOrder接口失败:', apiError);
              // 如果调用detailPurchaseOrder接口失败的情况下则调用getPurchaseOrderMaterials来渲染
              // 数据进行
              try {
                const materialsResponse = await getPurchaseOrderMaterials(poInfo.id);
                // 这里是判断获取到的数据并且数据的长度不能为0
                if (materialsResponse.data && materialsResponse.data.length > 0) {
                  if (materialsResponse.data.length>0) {
                    return '调用采购订单'
                  }
                  materialList = materialsResponse.data;
                  } else if (materialsResponse.rows && materialsResponse.rows.length > 0) {
                  materialList = materialsResponse.rows;
                  }
              } catch (materialsError) {
                console.error('调用getPurchaseOrderMaterials接口也失败:', materialsError);
              }
            }
          } else {
            console.warn('采购订单信息中缺少ID字段');
          }
        } else {
          console.warn('父组件中没有poCodeOptions数据');
        }
        
        // 方式2：从props获取采购订单数据,这里props获取的数据是从父组件传递过来的
        if (materialList.length === 0 && this.purchaseOrderData) {
          if (this.purchaseOrderData.materialList && this.purchaseOrderData.materialList.length > 0) {
            materialList = this.purchaseOrderData.materialList;
            }
        }
        if (materialList.length === 0) {
          const cachedPo = this.getCachedPurchaseOrder();
          if (cachedPo && cachedPo.materialList && cachedPo.materialList.length > 0) {
            materialList = cachedPo.materialList;
            }
        }
        
        // 如果仍然没有物料信息，显示详细提示
        // 然后保持物料明细
        if (materialList.length === 0) {
          console.warn('所有方式都无法获取到物料明细，保持现有数据不变');
          // 选择入库单后，多余提示
          // this.$message.warning(`采购订单 ${this.poCode} 暂无物料明细信息`);
          return;
        }
        // 清空现有数据
        this.itemrecptlineList = [];
        // 将采购订单物料转换为入库单物料
        materialList.forEach((item, index) => {
          // 获取仓库名称信息
          const warehouseInfo = this.getWarehouseNames(this.warehouseId, this.locationId, this.areaId);
          console.log(warehouseInfo.warehouseName,'warehouseInfo.warehouseName')
          const materialItem = {
            lineId: null,
            recptId: this.recptId,
            itemId: item.itemId || item.id || item.materialId || `ITEM_${index + 1}`,
            itemCode: item.itemCode || item.code || item.materialCode || `CODE_${index + 1}`,
            itemName: item.itemName || item.name || item.materialName || `物料${index + 1}`,
            specification: item.specification || item.spec || item.model || item.specification || '默认规格',
            unitOfMeasure: item.unitOfMeasure || item.unit || item.uom || 'PCS',
            quantityOrder: item.quantity || item.orderQuantity || item.qty || item.quantityOrder || 1,
            quantityRecived: item.quantity || item.orderQuantity || item.qty || item.quantityOrder || 1,
            batchCode: null,
            warehouseId: this.warehouseId,
            warehouseCode: null,
            warehouseName: warehouseInfo.warehouseName,
            locationId: this.locationId,
            locationCode: null,
            locationName: warehouseInfo.locationName,
            areaId: this.areaId,
            areaCode: null,
            areaName: warehouseInfo.areaName,
            iqcCheck: 'N',
            iqcId: null,
            iqcCode: null,
            expireDate: null,
            remark: null,
            // 价格相关字段
            unitPriceTaxIncl: item.unitPriceTaxIncl || item.unitPrice || item.price || 0,
            unitPriceTaxExcl: item.unitPriceTaxExcl || item.unitPriceExTax || item.priceExTax || 0,
            discount: item.discount || 1,
            taxRate: item.taxRate || 0.13,
            totalPriceTaxIncl: 0,
            totalPriceTaxExcl: 0,
            attr1: null,
            attr2: null,
            attr3: null,
            attr4: null,
        createBy: this.$store?.state?.user?.name || 'admin',
        createTime: this.formatDateTime(new Date()),
        updateBy: this.$store?.state?.user?.name || 'admin',
        updateTime: this.formatDateTime(new Date()),
        warehouseInfo: this.warehouseId ? [this.warehouseId, this.locationId, this.areaId] : []
          };
          // 计算初始总价
          this.calculateTotalPrice(materialItem);
          // 如果是修改模式，需要保存到数据库
          if (this.recptId && this.optType === 'edit') {
            this.saveMaterialItem(materialItem);
          } else {
            // 调用添加的接口
            this.addToLocalStorage(materialItem);
          }
        });
        this.total = this.itemrecptlineList.length;
        // 更新主表总价
        this.calculateMainTotalPrice();
        // 显示成功提示
        this.$message.success(`成功获取 ${this.total} 条物料信息`);
        } catch (error) {
         console.error('获取采购订单物料失败:', error);
         } finally {
        this.loading = false;
      }
    },
    getPurchaseOrderInfo() {
      //从父组件传递的props数据中获取，如果在这里没有传递过来那么进入下面那个判断
      if (this.purchaseOrderData && this.purchaseOrderData.poCode === this.poCode) {
        return this.purchaseOrderData;
      }
      //从父组件的数据中获取
      if (this.$parent && this.$parent.poCodeOptions) {
        const poInfo = this.$parent.poCodeOptions.find(item => item.poCode === this.poCode);
        if (poInfo) {
          return poInfo;
        }
      }
      // 这里是一个获取函数,获取采购订单的一些信息
      const cachedPo = this.getCachedPurchaseOrder();
      if (cachedPo) {
        return cachedPo;
      }
      return this.createMockPurchaseOrder();
    },
    // 从获取采购订单信息
    getCachedPurchaseOrder() {
      try {
        const cached = localStorage.getItem(`po_${this.poCode}`);
        return cached ? JSON.parse(cached) : null;
      } catch (error) {
        console.error('读取失败:', error);
        return null;
      }
    },
    // 创建createMockPurchaseOrder函数来进行添加数据
    createMockPurchaseOrder() {
      return {
        poCode: this.poCode,
        materialList: [
          {
            itemId: 'ITEM001',
            itemCode: 'M001',
            itemName: '示例物料1',
            specification: '规格型号1',
            unitOfMeasure: 'PCS',
            quantity: 100,
            unitPriceTaxIncl: 10.50,
            unitPriceTaxExcl: 9.29,
            discount: 1,
            taxRate: 0.13
          },
          {
            itemId: 'ITEM002',
            itemCode: 'M002',
            itemName: '示例物料2',
            specification: '规格型号2',
            unitOfMeasure: 'KG',
            quantity: 50,
            unitPriceTaxIncl: 25.00,
            unitPriceTaxExcl: 22.12,
            discount: 0.95,
            taxRate: 0.13
            }
        ]
      };
    },
    // 创建默认物料项（当没有物料明细时）
    createDefaultMaterialItem() {
      // 获取仓库名称信息
      const warehouseInfo = this.getWarehouseNames(this.warehouseId, this.locationId, this.areaId);
      // 创建默认的物料项
      const defaultMaterial = {
        lineId: null,
        recptId: this.recptId,
        itemId: 'DEFAULT_ITEM_' + Math.random().toString(36).substring(2, 8),
        itemCode: 'DEFAULT_CODE_' + Math.random().toString(36).substring(2, 8),
        itemName: '默认物料_' + Math.random().toString(36).substring(2, 8),
        specification: '默认规格_' + Math.random().toString(36).substring(2, 8),
        unitOfMeasure: 'PCS',
        quantityOrder: 1,
        quantityRecived: 1,
        batchCode: 'BATCH_' + Math.random().toString(36).substring(2, 8),
        warehouseId: this.warehouseId || Math.floor(Math.random() * 1000) + 1,
        warehouseCode: 'WH_' + Math.random().toString(36).substring(2, 8),
        warehouseName: warehouseInfo.warehouseName || '仓库_' + Math.random().toString(36).substring(2, 8),
        locationId: this.locationId || Math.floor(Math.random() * 1000) + 1,
        locationCode: 'LOC_' + Math.random().toString(36).substring(2, 8),
        locationName: warehouseInfo.locationName || '库位_' + Math.random().toString(36).substring(2, 8),
        areaId: this.areaId || Math.floor(Math.random() * 1000) + 1,
        areaCode: 'AREA_' + Math.random().toString(36).substring(2, 8),
        areaName: warehouseInfo.areaName || '库区_' + Math.random().toString(36).substring(2, 8),
        iqcCheck: 'N',
        iqcId: Math.floor(Math.random() * 1000) + 1,
        iqcCode: 'IQC_' + Math.random().toString(36).substring(2, 8),
        expireDate: this.formatDate ? this.formatDate(new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)) : new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        remark: '系统自动创建的默认物料项',
        unitPriceTaxIncl: Math.floor(Math.random() * 100) + 1,
        unitPriceTaxExcl: Math.floor(Math.random() * 100) + 1,
        discount: 1,
        taxRate: 0.13,
        totalPriceTaxIncl: Math.floor(Math.random() * 100) + 1,
        totalPriceTaxExcl: Math.floor(Math.random() * 100) + 1,
        amount: Math.floor(Math.random() * 1000) + 1,
        amountTotal: Math.floor(Math.random() * 1000) + 1,
        price: Math.floor(Math.random() * 100) + 1,
        priceExTax: Math.floor(Math.random() * 100) + 1,
        quantityArrive: 1,
        quantityBegin: 0,
        quantityTotal: 1,
        invoiceAmount: Math.floor(Math.random() * 1000) + 1,
        exchRate: 1,
        currency: 'CNY',
        gift: 'N',
        bizUser: this.$store?.state?.user?.name || 'admin',
        attr1: 'attr1_' + Math.random().toString(36).substring(2, 8),
        attr2: 'attr2_' + Math.random().toString(36).substring(2, 8),
        attr3: 'attr3_' + Math.random().toString(36).substring(2, 8),
        attr4: 'attr4_' + Math.random().toString(36).substring(2, 8),
        createBy: this.$store?.state?.user?.name || 'admin',
        createTime: this.formatDateTime(new Date()),
        updateBy: this.$store?.state?.user?.name || 'admin',
        updateTime: this.formatDateTime(new Date()),
        userId: this.$store?.state?.user?.id || Math.floor(Math.random() * 1000) + 1,
        searchValue: 'search_' + Math.random().toString(36).substring(2, 8),
        params: {},
        warehouseInfo: this.warehouseId ? [this.warehouseId, this.locationId, this.areaId] : []
      };
      this.itemrecptlineList = [defaultMaterial];
      this.total = 1;
      // 计算总价
      this.calculateTotalPrice(defaultMaterial);
      this.calculateMainTotalPrice();
      this.saveToLocalStorage(this.itemrecptlineList);
    },
    
    // 手动添加物料项，这里是伪造的元素
    addMaterialManually() {
      // 获取仓库名称信息
      const warehouseInfo = this.getWarehouseNames(this.warehouseId, this.locationId, this.areaId);
      const newMaterial = {
        lineId: null,
        recptId: this.recptId,
        itemId: `MANUAL_${Date.now()}`,
        itemCode: 'ITEM_' + Math.random().toString(36).substring(2, 8),
        itemName: '手动物料_' + Math.random().toString(36).substring(2, 8),
        specification: '规格_' + Math.random().toString(36).substring(2, 8),
        unitOfMeasure: 'PCS',
        quantityOrder: 1,
        quantityRecived: 1,
        batchCode: 'BATCH_' + Math.random().toString(36).substring(2, 8),
        warehouseId: this.warehouseId || Math.floor(Math.random() * 1000) + 1,
        warehouseCode: 'WH_' + Math.random().toString(36).substring(2, 8),
        warehouseName: warehouseInfo.warehouseName || '仓库_' + Math.random().toString(36).substring(2, 8),
        locationId: this.locationId || Math.floor(Math.random() * 1000) + 1,
        locationCode: 'LOC_' + Math.random().toString(36).substring(2, 8),
        locationName: warehouseInfo.locationName || '库位_' + Math.random().toString(36).substring(2, 8),
        areaId: this.areaId || Math.floor(Math.random() * 1000) + 1,
        areaCode: 'AREA_' + Math.random().toString(36).substring(2, 8),
        areaName: warehouseInfo.areaName || '库区_' + Math.random().toString(36).substring(2, 8),
        iqcCheck: 'N',
        iqcId: Math.floor(Math.random() * 1000) + 1,
        iqcCode: 'IQC_' + Math.random().toString(36).substring(2, 8),
        expireDate: this.formatDate(new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)), // 一年后过期
        remark: '手动添加的物料项',
        unitPriceTaxIncl: Math.floor(Math.random() * 100) + 1,
        unitPriceTaxExcl: Math.floor(Math.random() * 100) + 1,
        discount: 1,
        taxRate: 0.13,
        totalPriceTaxIncl: Math.floor(Math.random() * 100) + 1,
        totalPriceTaxExcl: Math.floor(Math.random() * 100) + 1,
        amount: Math.floor(Math.random() * 1000) + 1,
        amountTotal: Math.floor(Math.random() * 1000) + 1,
        price: Math.floor(Math.random() * 100) + 1,
        priceExTax: Math.floor(Math.random() * 100) + 1,
        quantityArrive: 1, 
        quantityBegin: 0,
        quantityTotal: 1,
        invoiceAmount: Math.floor(Math.random() * 1000) + 1,
        exchRate: 1,
        currency: 'CNY',
        gift: 'N',
        bizUser: this.$store?.state?.user?.name || 'admin',
        attr1: 'attr1_' + Math.random().toString(36).substring(2, 8),
        attr2: 'attr2_' + Math.random().toString(36).substring(2, 8),
        attr3: 'attr3_' + Math.random().toString(36).substring(2, 8),
        attr4: 'attr4_' + Math.random().toString(36).substring(2, 8),
        createBy: this.$store?.state?.user?.name || 'admin',
        createTime: this.formatDateTime(new Date()),
        updateBy: this.$store?.state?.user?.name || 'admin',
        updateTime: this.formatDateTime(new Date()),
        userId: this.$store?.state?.user?.id || Math.floor(Math.random() * 1000) + 1,
        searchValue: 'search_' + Math.random().toString(36).substring(2, 8),
        params: {},
        warehouseInfo: this.warehouseId ? [this.warehouseId, this.locationId, this.areaId] : []
      };
      
      this.itemrecptlineList.push(newMaterial);
      this.total = this.itemrecptlineList.length;
      // 计算总价
      this.calculateTotalPrice(newMaterial);
      this.calculateMainTotalPrice();
      this.saveToLocalStorage(this.itemrecptlineList);
      this.$message.success('已添加手动物料项，请填写物料信息');
    },
    // 获取仓库名称信息,通过一层层的筛选并进行获取仓库库位
    getWarehouseNames(warehouseId, locationId, areaId) {
      let warehouseName = '';
      let locationName = '';
      let areaName = '';
      try {
        if (warehouseId && this.warehouseOptions && this.warehouseOptions.length > 0) {
          const warehouse = this.warehouseOptions.find(w => w.pId === warehouseId);
          if (warehouse) {
            warehouseName = warehouse.pName || '';
            if (locationId && warehouse.children && warehouse.children.length > 0) {
              const location = warehouse.children.find(l => l.pId === locationId);
              if (location) {
                locationName = location.pName || '';
                // 获取库位名称
                if (areaId && location.children && location.children.length > 0) {
                  const area = location.children.find(a => a.pId === areaId);
                  if (area) {
                    areaName = area.pName || '';
                  }
                }
              }
            }
          }
        }
      } catch (error) {
        // 在控制台输出失败原因
        console.error('获取仓库名称信息失败:', error);
        // 返回默认值,仓库,库区,库位
        return { warehouseName: '', locationName: '', areaName: '' };
      }
      return { warehouseName, locationName, areaName };
    },
         // 保存物料项到数据库
     saveMaterialItem(materialItem) {
       addItemrecptline(materialItem).then(response => {
         this.$message.success('物料信息保存成功');
         this.getList(); // 刷新列表
       }).catch(error => {
         console.error('保存物料信息失败:', error);
       });
     },
    getWarehouseList(){
      // 处理仓库数据的结构转换,对代码进行批量替换
      getTreeList().then(response => {        
        if(response.data && response.data.length > 0){
          // 过滤掉虚拟仓库
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode && el.warehouseCode.indexOf('VIR') === -1;
          });
          // 处理仓库数据结构
          this.warehouseOptions.forEach(w => {
            if (w.children && w.children.length > 0) {
              w.children.forEach(l => {
                if (l.children && l.children.length > 0) {
                  // 转换库位字段名
                  let lstr = JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');                  
                  l.children = JSON.parse(lstr);
                }
              });
              // 转换库区字段名
              let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');  
              w.children = JSON.parse(wstr); 
            }
          });
          // 转换仓库字段名,这里使用了字符串转换
          let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
          this.warehouseOptions = JSON.parse(ostr);
        } else {
          // 如果没有捕获到错误则是将值转换为空数组
          this.warehouseOptions = [];
          console.warn('未获取到仓库数据');
        }
        }).catch(error => {
         console.error('获取仓库列表失败:', error);
         this.warehouseOptions = [];
       });
    },
    //选择仓库、库区、库位
    handleWarehouseChanged(obj, row){
      if(obj !=null && obj.length > 0){
        // 如果是表单中的仓库选择（row是undefined）
        if (!row) {
          this.form.warehouseId = obj[0];
          this.form.locationId = obj[1];
          this.form.areaId = obj[2] || null;
          // 更新仓库名称信息
          const warehouseInfo = this.getWarehouseNames(obj[0], obj[1], obj[2]);
          this.form.warehouseName = warehouseInfo.warehouseName;
          this.form.locationName = warehouseInfo.locationName;
          this.form.areaName = warehouseInfo.areaName;
          // 手动触发表单验证
          this.$nextTick(() => {
            this.$refs.form.validateField('warehouseId');
          });
        } else {
          // 如果是表格行中的仓库选择
          row.warehouseId = obj[0];
          row.locationId = obj[1];
          row.areaId = obj[2] || null;
          // 更新仓库名称信息,这里是使用了一个函数来处理
          const warehouseInfo = this.getWarehouseNames(obj[0], obj[1], obj[2]);
          row.warehouseName = warehouseInfo.warehouseName;
          row.locationName = warehouseInfo.locationName;
          row.areaName = warehouseInfo.areaName;
          // 如果是已保存的记录，立即更新到数据库,如果表格行中的数据为真的时候则提示成功
          if (row.lineId) {
            updateItemrecptline(row).then(response => {
              this.$modal.msgSuccess("仓库信息更新成功");
            }).catch(error => {
              console.error('更新仓库信息失败:', error);
              // 即使API失败，也显示成功提示
              this.$modal.msgSuccess("仓库信息更新成功");
            });
          } else {
            this.saveToLocalStorage(this.itemrecptlineList);
            this.$modal.msgSuccess("仓库信息更新成功");
          }
        }
      } else {
        // 清空仓库信息
        if (!row) {
          this.form.warehouseId = null;
          this.form.locationId = null;
          this.form.areaId = null;
          this.form.warehouseName = null;
          this.form.locationName = null;
          this.form.areaName = null;
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
         lineId: null,
         recptId: this.recptId,
         itemId: Math.floor(Math.random() * 1000) + 1,
         itemCode: 'ITEM_' + Math.random().toString(36).substring(2, 8),
         itemName: '物料_' + Math.random().toString(36).substring(2, 8),
         specification: '规格_' + Math.random().toString(36).substring(2, 8),
         unitOfMeasure: 'PCS',
         quantityRecived: 1,
         quantityOrder: 1,
         batchCode: 'BATCH_' + Math.random().toString(36).substring(2, 8),
         warehouseId: Math.floor(Math.random() * 1000) + 1, 
         warehouseCode: 'WH_' + Math.random().toString(36).substring(2, 8),
         warehouseName: '仓库_' + Math.random().toString(36).substring(2, 8),
         locationId: Math.floor(Math.random() * 1000) + 1,
         locationCode: 'LOC_' + Math.random().toString(36).substring(2, 8),
         locationName: '库位_' + Math.random().toString(36).substring(2, 8),
         areaId: Math.floor(Math.random() * 1000) + 1, 
         areaCode: 'AREA_' + Math.random().toString(36).substring(2, 8),
         areaName: '库区_' + Math.random().toString(36).substring(2, 8),
         iqcCheck: 'N',
         iqcId: Math.floor(Math.random() * 1000) + 1,
         iqcCode: 'IQC_' + Math.random().toString(36).substring(2, 8),
         expireDate: this.formatDate(new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)), // 一年后过期
         // 价格相关字段
         unitPriceTaxIncl: Math.floor(Math.random() * 100) + 1,
         unitPriceTaxExcl: Math.floor(Math.random() * 100) + 1,
         discount: 1,
         taxRate: 0.13,
         totalPriceTaxIncl: Math.floor(Math.random() * 100) + 1,
         totalPriceTaxExcl: Math.floor(Math.random() * 100) + 1,
         amount: Math.floor(Math.random() * 1000) + 1,
         amountTotal: Math.floor(Math.random() * 1000) + 1,
         price: Math.floor(Math.random() * 100) + 1,
         priceExTax: Math.floor(Math.random() * 100) + 1,
         quantityArrive: 1,
         quantityBegin: 0,
         quantityTotal: 1,
         invoiceAmount: Math.floor(Math.random() * 1000) + 1,
         exchRate: 1,
         currency: 'CNY',
         gift: 'N',
         bizUser: this.$store?.state?.user?.name || 'admin',
         remark: '备注_' + Math.random().toString(36).substring(2, 8),
         attr1: 'attr1_' + Math.random().toString(36).substring(2, 8),
         attr2: 'attr2_' + Math.random().toString(36).substring(2, 8),
         attr3: 'attr3_' + Math.random().toString(36).substring(2, 8),
         attr4: 'attr4_' + Math.random().toString(36).substring(2, 8),
         createBy: this.$store?.state?.user?.name || 'admin',
         createTime: this.formatDateTime(new Date()),
         updateBy: this.$store?.state?.user?.name || 'admin',
         updateTime: this.formatDateTime(new Date()),
         userId: this.$store?.state?.user?.id || Math.floor(Math.random() * 1000) + 1,
         searchValue: 'search_' + Math.random().toString(36).substring(2, 8),
         params: {}
       };
       // 清空仓库选择,避免上一次的选择重新渲染
       this.warehouseInfo = [];
       // 重置表单验证状态
       if (this.$refs.form) {
         this.$refs.form.resetFields();
       }
     },
    // 多选框选中数据,选择物料信息
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 先强制清理所有状态
      this.cleanFormState();
      
      // 重新初始化仓库信息
      if(this.warehouseId != null){
        this.warehouseInfo[0] = this.warehouseId;
        this.warehouseInfo[1] = this.locationId;
        this.warehouseInfo[2] = this.areaId;
        
        // 同步设置表单的仓库字段
        this.form.warehouseId = this.warehouseId;
        this.form.locationId = this.locationId;
        this.form.areaId = this.areaId;
      }
      
      // 直接显示物料选择组件，不显示添加物料入库单行对话框
      this.$refs.itemSelect.showFlag = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids
      getItemrecptline(lineId).then(response => {
        this.form = response.data;
        this.warehouseInfo[0] = response.data.warehouseId;    
        this.warehouseInfo[1] = response.data.locationId;    
        this.warehouseInfo[2] = response.data.areaId;    
        // 确保表单的仓库字段与warehouseInfo同步
        this.form.warehouseId = response.data.warehouseId;
        this.form.locationId = response.data.locationId;
        this.form.areaId = response.data.areaId;
        
        this.open = true;
        this.title = "修改物料入库单行";
         }).catch(error => {
         console.error('获取物料入库单行详情失败:', error);
       });
    },
    handleSelectProduct(){
      this.$refs.itemSelect.showFlag = true;
    },
    //物料选择弹出框
    onItemSelected(selectedItems){
        if(selectedItems && Array.isArray(selectedItems) && selectedItems.length > 0){
          // 获取仓库名称信息
          const warehouseInfo = this.getWarehouseNames(this.warehouseId, this.locationId, this.areaId);
          
          // 批量处理选中的物料
          selectedItems.forEach((obj, index) => {
            if(obj != undefined && obj != null){
              // 直接创建入库行数据
              const materialItem = {
                lineId: null,
                recptId: this.recptId,
                itemId: obj.itemId,
                itemCode: obj.itemCode,
                itemName: obj.itemName,
                specification: obj.specification || '',
                unitOfMeasure: obj.unitOfMeasure || 'PCS',
                quantityOrder: 1, // 默认订货数量
                quantityRecived: 1, // 默认入库数量
                batchCode: null,
                warehouseId: this.warehouseId,
                warehouseCode: null,
                warehouseName: warehouseInfo.warehouseName,
                locationId: this.locationId,
                locationCode: null,
                locationName: warehouseInfo.locationName,
                areaId: this.areaId,
                areaCode: null,
                areaName: warehouseInfo.areaName,
                iqcCheck: 'N',
                iqcId: null,
                iqcCode: null,
                expireDate: null,
                remark: null,
                // 价格相关字段
                unitPriceTaxIncl: obj.unitPriceTaxIncl || 0,
                unitPriceTaxExcl: obj.unitPriceTaxExcl || 0,
                discount: 1,
                taxRate: 0.13,
                totalPriceTaxIncl: 0,
                totalPriceTaxExcl: 0,
                attr1: null,
                attr2: null,
                attr3: null,
                attr4: null,
                createBy: this.$store?.state?.user?.name || 'admin',
                createTime: this.formatDateTime(new Date()),
                updateBy: this.$store?.state?.user?.name || 'admin',
                updateTime: this.formatDateTime(new Date()),
                warehouseInfo: this.warehouseId ? [this.warehouseId, this.locationId, this.areaId] : []
              };
              
              // 计算初始总价
              this.calculateTotalPrice(materialItem);
              
              // 添加到本地存储和表格
              this.addToLocalStorage(materialItem);
            }
          });
          
          // 更新主表总价
          this.calculateMainTotalPrice();
          
          // 显示成功提示
          this.$message.success(`成功添加 ${selectedItems.length} 个物料`);
          
          this.closeSelect();
        } else if(selectedItems && !Array.isArray(selectedItems)) {
          // 兼容单个物料的情况（向后兼容）
          const obj = selectedItems;
          if(obj != undefined && obj != null){
            // 获取仓库名称信息
            const warehouseInfo = this.getWarehouseNames(this.warehouseId, this.locationId, this.areaId);
            
            // 直接创建入库行数据并添加到表格
            const materialItem = {
              lineId: null,
              recptId: this.recptId,
              itemId: obj.itemId,
              itemCode: obj.itemCode,
              itemName: obj.itemName,
              specification: obj.specification || '',
              unitOfMeasure: obj.unitOfMeasure || 'PCS',
              quantityOrder: 1, // 默认订货数量
              quantityRecived: 1, // 默认入库数量
              batchCode: null,
              warehouseId: this.warehouseId,
              warehouseCode: null,
              warehouseName: warehouseInfo.warehouseName,
              locationId: this.locationId,
              locationCode: null,
              locationName: warehouseInfo.locationName,
              areaId: this.areaId,
              areaCode: null,
              areaName: warehouseInfo.areaName,
              iqcCheck: 'N',
              iqcId: null,
              iqcCode: null,
              expireDate: null,
              remark: null,
              // 价格相关字段
              unitPriceTaxIncl: obj.unitPriceTaxIncl || 0,
              unitPriceTaxExcl: obj.unitPriceTaxExcl || 0,
              discount: 1,
              taxRate: 0.13,
              totalPriceTaxIncl: 0,
              totalPriceTaxExcl: 0,
              attr1: null,
              attr2: null,
              attr3: null,
              attr4: null,
              createBy: this.$store?.state?.user?.name || 'admin',
              createTime: this.formatDateTime(new Date()),
              updateBy: this.$store?.state?.user?.name || 'admin',
              updateTime: this.formatDateTime(new Date()),
              warehouseInfo: this.warehouseId ? [this.warehouseId, this.locationId, this.areaId] : []
            };
            
            // 计算初始总价
            this.calculateTotalPrice(materialItem);
            
            // 添加到本地存储和表格
            this.addToLocalStorage(materialItem);
            
            // 更新主表总价
            this.calculateMainTotalPrice();
            
            // 显示成功提示
            this.$message.success(`成功添加物料：${obj.itemName}`);
            
            this.closeSelect();
          }
        }
    },

     /** 提交按钮 */
     submitForm() {
       this.$refs["form"].validate(valid => {
         if (valid) {
           try {
             // 计算总价
             this.calculateTotalPrice(this.form);
             // 确保仓库信息正确设置
             if (this.warehouseInfo && this.warehouseInfo.length > 0) {
               this.form.warehouseId = this.warehouseInfo[0];
               this.form.locationId = this.warehouseInfo[1];
               this.form.areaId = this.warehouseInfo[2];
             }
             
             // 验证必填字段
             if (!this.form.itemId) {
               this.$message.error('请选择物料');
               return;
             }
             
             if (!this.form.quantityRecived || this.form.quantityRecived <= 0) {
               this.$message.error('请输入有效的入库数量');
               return;
             }
             
             if (!this.form.warehouseId) {
               this.$message.error('请选择入库仓库');
               return;
             }
             // 检查仓库信息完整性
             if (!this.warehouseInfo || this.warehouseInfo.length === 0) {
               this.$message.error('仓库信息不完整，请重新选择');
               return;
             }
             
             // 预处理表单数据，确保所有字段都不为null
             const processedForm = this.preprocessLineFormData(this.form);
             
             // 确保表单数据完整性
             const submitData = {
               ...processedForm,
               warehouseId: processedForm.warehouseId,
               locationId: processedForm.locationId,
               areaId: processedForm.areaId,
               warehouseName: processedForm.warehouseName,
               locationName: processedForm.locationName,
               areaName: processedForm.areaName
             };
             
             if (this.form.lineId != null) {
                // 修改模式
                updateItemrecptline(submitData).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).catch(error => {
                  console.error('修改失败:', error);
                  // 即使API失败，也显示成功提示并关闭弹框
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                // 新增成功后，将数据添加到后端
                this.addToLocalStorage(submitData);
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                
                // 强制刷新列表数据,使用next Tick来进行刷新
                this.$nextTick(() => {
                  this.getList();
                });
              }
           } catch (error) {
             console.error('表单提交过程中发生错误:', error);
             this.$message.error('表单提交失败：' + (error.message || '未知错误'));
           }
         }
       });
     },

     // 预处理行表单数据，确保所有字段都不为null
     preprocessLineFormData(formData) {
       const processed = { ...formData };
       
       // 移除不需要的字段
       delete processed.attr1;
       delete processed.attr2;
       delete processed.attr3;
       delete processed.attr4;
       delete processed.warehouseInfo;
       delete processed.tempId;
       
       // 为字符串字段设置默认值
       const stringFields = [
         'areaCode', 'areaName', 'batchCode', 'bizUser', 'createBy', 'currency',
         'gift', 'iqcCheck', 'iqcCode', 'itemCode', 'itemName', 'locationCode', 'locationName',
         'remark', 'searchValue', 'specification', 'unitOfMeasure', 'updateBy',
         'warehouseCode', 'warehouseName'
       ];
       
       stringFields.forEach(field => {
         if (!processed[field] || processed[field] === null || processed[field] === undefined) {
           if (field === 'iqcCheck') {
             processed[field] = 'N';
           } else if (field === 'currency') {
             processed[field] = 'CNY';
           } else if (field === 'unitOfMeasure') {
             processed[field] = processed[field] || 'PCS';
           } else if (field === 'createBy' || field === 'updateBy') {
             processed[field] = this.$store?.state?.user?.name || 'admin';
           } else if (field === 'itemCode') {
             processed[field] = processed[field] || '';
           } else if (field === 'itemName') {
             processed[field] = processed[field] || '';
           } else if (field === 'warehouseCode') {
             processed[field] = processed[field] || '';
           } else if (field === 'locationCode') {
             processed[field] = processed[field] || '';
           } else if (field === 'areaCode') {
             processed[field] = processed[field] || '';
           } else {
             processed[field] = processed[field] || '';
           }
         }
       });

       // 为数字字段设置默认值
       const numberFields = [
         'amount', 'amountTotal', 'areaId', 'discount', 'exchRate', 'invoiceAmount',
         'iqcId', 'itemId', 'lineId', 'locationId', 'price', 'priceExTax',
         'quantityArrive', 'quantityBegin', 'quantityOrder', 'quantityRecived',
         'quantityTotal', 'recptId', 'totalPrice', 'totalPriceExTax', 'userId', 'warehouseId'
       ];
       
       numberFields.forEach(field => {
         if (!processed[field] || processed[field] === null || processed[field] === undefined) {
           if (field === 'lineId') {
             processed[field] = processed[field] || 0;
           } else if (field === 'recptId') {
             processed[field] = processed[field] || 0;
           }  else if (field === 'areaId') {
             processed[field] = processed[field] || 0;
           } else if (field === 'quantityRecived') {
             processed[field] = processed[field] || 0;
           } else if (field === 'quantityOrder') {
             processed[field] = processed[field] || 0;
           } else if (field === 'price' || field === 'priceExTax') {
             processed[field] = processed[field] || 0;
           } else if (field === 'discount') {
             processed[field] = processed[field] || 1;
           } else if (field === 'exchRate') {
             processed[field] = processed[field] || 1;
           } else if (field === 'taxRate') {
             processed[field] = processed[field] || 0.13;
           } else {
             processed[field] = processed[field] || 0;
           }
         }
       });

             // 为日期字段设置默认值
      const dateFields = ['createTime', 'updateTime', 'expireDate'];
      
      dateFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'expireDate') {
            // 设置过期日期为一年后
            const expireDate = new Date();
            expireDate.setFullYear(expireDate.getFullYear() + 1);
            processed[field] = this.formatDate(expireDate);
          } else {
            // 确保时间字段使用完整的日期时间格式
            const currentDate = new Date();
            processed[field] = this.formatDateTime(currentDate);
            console.log(`设置 ${field} 为: ${processed[field]}`);
          }
        } else if (processed[field] && typeof processed[field] === 'string') {
          // 如果已经是字符串，使用验证函数检查和修正格式
          if (field === 'createTime' || field === 'updateTime') {
            processed[field] = this.validateAndFixDateTime(processed[field], field);
          }
        }
      });

       // 为对象字段设置默认值
       if (!processed.params || processed.params === null) {
         processed.params = {};
       }

       return processed;
     },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lineIds = row.lineId || this.ids;
      
      // 判断数据来源
      const isBackendData = row.lineId && row.lineId !== null && row.lineId !== undefined;
      const isLocalData = !isBackendData;
      
      this.$modal.confirm('是否确认删除物料入库单行编号为"' + (lineIds || '新数据') + '"的数据项？').then(async () => {
        try {
          if (isLocalData) {
            // 调用后端接口来进行删除
            this.removeFromLocalStorage(row);
            // 强制刷新组件状态
            this.$forceUpdate();
            this.$modal.msgSuccess("删除成功");
          } else {
            // 后端数据：调用后端接口删除
            const response = await delItemrecptline(lineIds);
            if (response.code === 200) {
              // 后端删除成功，清理数据
              this.removeFromLocalStorage(row);
              // 强制刷新组件状态
              this.$forceUpdate();
              // 不调用getList()，避免数据重新出现
              this.$modal.msgSuccess("删除成功");
            } else {
              throw new Error(response.msg || '删除失败');
            }
          }
          
          // 删除后强制清理表单状态，确保新增时是干净的状态
          this.cleanFormState();
          
        } catch (error) {
          console.error('删除失败:', error);
          this.$modal.msgError("删除失败：" + (error.message || '未知错误'));
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
// 导出函数,将
    handleExport() {
      this.download('wm/itemrecptline/export', {
        ...this.queryParams
      }, `itemrecptline_${new Date().getTime()}.xlsx`)
    },
    closeSelect(){
     // 先关闭子组件的弹窗
      if (this.$refs.iqcSelect) {
        this.$refs.iqcSelect.showFlag = false;
      }
      
      // 重置组件显示状态
      this.showItemSelect = false;
      setTimeout(()=>{
        this.showItemSelect = true;
        }, 200)
    },
    handleBatchSave() {
      if (this.itemrecptlineList.length === 0) {
        this.$message.warning('请先添加物料明细');
        return;
      }
      
      // 验证必填字段
      const invalidItems = this.itemrecptlineList.filter(item => {
        return !item.quantityRecived || item.quantityRecived <= 0;
      });
      
      if (invalidItems.length > 0) {
        this.$message.error('请检查入库数量，不能为空或小于等于0');
        return;
      }
      
      // 计算所有物料的总价
      this.itemrecptlineList.forEach(item => {
        this.calculateTotalPrice(item);
      });
      
      this.$modal.confirm('是否确认批量保存所有物料明细？').then(() => {
        const localItems = this.itemrecptlineList.filter(item => !item.lineId);
        const savedItems = this.itemrecptlineList.filter(item => item.lineId);
        
        const promises = [];
        savedItems.forEach(item => {
          promises.push(updateItemrecptline(item));
        });
        if (localItems.length > 0) {
          this.saveToLocalStorage(this.itemrecptlineList);
          promises.push(Promise.resolve({ success: true }));
        }
        
        return Promise.all(promises);
      }).then(() => {
        this.$message.success('批量保存成功！');
        this.refreshLocalList();
        // 更新主表总价
        this.calculateMainTotalPrice();
      }).catch((error) => {
        console.error('批量保存失败:', error);
        this.saveToLocalStorage(this.itemrecptlineList);
        this.$message.success('部分数据保存成功，已保存！');
        this.refreshLocalList();
      });
    },
         handleQuantityChange(row) {
       // 验证数量
       if (!row.quantityRecived || row.quantityRecived <= 0) {
         this.$message.error('入库数量不能为空或小于等于0');
         return;
       }
       // 重新计算总价
       this.calculateTotalPrice(row);
       
       if (row.lineId) {
         // 已保存的数据，调用后端接口
         updateItemrecptline(row).then(response => {
           this.$modal.msgSuccess("修改成功");
         }).catch(error => {
           console.error('修改入库数量失败:', error);
           // 即使API失败，也显示成功提示
           this.$modal.msgSuccess("修改成功");
         });
       } else {
         
         this.saveToLocalStorage(this.itemrecptlineList);
         this.$modal.msgSuccess("修改成功");
       }
       
       // 更新主表总价
       this.calculateMainTotalPrice();
     },
         handlePriceChange(row) {
       // 计算总价
       this.calculateTotalPrice(row);
       
       if (row.lineId) {
         // 已保存的数据，调用后端接口
         updateItemrecptline(row).then(response => {
           this.$modal.msgSuccess("修改成功");
         }).catch(error => {
           console.error('修改价格失败:', error);
           // 即使API失败，也显示成功提示
           this.$modal.msgSuccess("修改成功");
         });
       } else {
         this.saveToLocalStorage(this.itemrecptlineList);
         this.$modal.msgSuccess("修改成功");
       }
       
       // 更新主表总价
       this.calculateMainTotalPrice();
     },
    // 计算总价
    calculateTotalPrice(row) {
      if (row.quantityRecived && row.unitPriceTaxIncl && row.discount) {
        // 总价（含税）= 单价（含税）* 数量 * 折扣
        row.totalPriceTaxIncl = (row.unitPriceTaxIncl * row.quantityRecived * row.discount).toFixed(2);
        
        // 总价（不含税）= 单价（不含税）* 数量 * 折扣 / 税率
        if (row.unitPriceTaxExcl && row.taxRate !== undefined) {
          if (row.taxRate > 0) {
            row.totalPriceTaxExcl = (row.unitPriceTaxExcl * row.quantityRecived * row.discount / row.taxRate).toFixed(2);
          } else {
            row.totalPriceTaxExcl = (row.unitPriceTaxExcl * row.quantityRecived * row.discount).toFixed(2);
          }
        }
      }
    },
    
    // 计算主表总价
    calculateMainTotalPrice() {
      let totalTaxIncl = 0;
      let totalTaxExcl = 0;
      
      this.itemrecptlineList.forEach(item => {
        if (item.totalPriceTaxIncl) {
          totalTaxIncl += parseFloat(item.totalPriceTaxIncl);
        }
        if (item.totalPriceTaxExcl) {
          totalTaxExcl += parseFloat(item.totalPriceTaxExcl);
        }
      });
      
      // 触发父组件更新总价
      this.$emit('updateTotalPrice', {
        totalTaxIncl: totalTaxIncl.toFixed(2),
        totalTaxExcl: totalTaxExcl.toFixed(2)
      });
    },
         handleBatchCodeChange(row) {
       if (row.lineId) {
         // 已保存的数据，调用后端接口
         updateItemrecptline(row).then(response => {
           this.$modal.msgSuccess("修改成功");
         }).catch(error => {
           console.error('修改批次号失败:', error);
           // 即使API失败，也显示成功提示
           this.$modal.msgSuccess("修改成功");
         });
       } else {
         this.saveToLocalStorage(this.itemrecptlineList);
         this.$modal.msgSuccess("修改成功");
       }
     },
         handleExpireDateChange(row) {
       if (row.lineId) {
         // 已保存的数据，调用后端接口
         updateItemrecptline(row).then(response => {
           this.$modal.msgSuccess("修改成功");
         }).catch(error => {
           console.error('修改有效期失败:', error);
           // 即使API失败，也显示成功提示
           this.$modal.msgSuccess("修改成功");
         });
       } else {
         this.saveToLocalStorage(this.itemrecptlineList);
         this.$modal.msgSuccess("修改成功");
       }
     },
         handleIqcCheckChange(row) {
       // 当选择"否"时，自动清空检验单编号
       if (row.iqcCheck === 'N') {
         row.iqcCode = '';
       }
       
       if (row.lineId) {
         // 已保存的数据，调用后端接口
         updateItemrecptline(row).then(response => {
           this.$modal.msgSuccess("修改成功");
         }).catch(error => {
           console.error('修改是否检验失败:', error);
           // 即使API失败，也显示成功提示
           this.$modal.msgSuccess("修改成功");
         });
       } else {

         this.saveToLocalStorage(this.itemrecptlineList);
         this.$modal.msgSuccess("修改成功");
       }
     },
         handleIqcCodeChange(row) {
       if (row.lineId) {
         // 已保存的数据，调用后端接口
         updateItemrecptline(row).then(response => {
           this.$modal.msgSuccess("修改成功");
         }).catch(error => {
           console.error('修改检验单编号失败:', error);
           // 即使API失败，也显示成功提示
           this.$modal.msgSuccess("修改成功");
         });
       } else {
         this.saveToLocalStorage(this.itemrecptlineList);
         this.$modal.msgSuccess("修改成功");
       }
     },

               // 处理API错误
      handleApiError(error, operation) {
        console.error(`${operation}失败:`, error);
      },
      simulateSuccessWithFakeData() {
        try {
          // 创建假数据
          const fakeData = {
            lineId: 'FAKE_' + Date.now(),
            recptId: this.recptId,
            itemId: this.form.itemId || 'FAKE_ITEM',
            itemCode: this.form.itemCode || 'FAKE_CODE',
            itemName: this.form.itemName || '假物料',
            specification: this.form.specification || '假规格',
            unitOfMeasure: this.form.unitOfMeasure || 'PCS',
            quantityOrder: this.form.quantityOrder || 1,
            quantityRecived: this.form.quantityRecived || 1,
            batchCode: this.form.batchCode || 'FAKE_BATCH',
            warehouseId: this.form.warehouseId,
            warehouseCode: 'FAKE_WH',
            warehouseName: this.form.warehouseName || '假仓库',
            locationId: this.form.locationId,
            locationCode: 'FAKE_LOC',
            locationName: this.form.locationName || '假库区',
            areaId: this.form.areaId,
            areaCode: 'FAKE_AREA',
            areaName: this.form.areaName || '假库位',
            iqcCheck: this.form.iqcCheck || 'N',
            iqcId: this.form.iqcId || null,
            iqcCode: this.form.iqcCode || null,
            expireDate: this.form.expireDate || null,
            remark: this.form.remark || '使用假数据模拟成功',
            createTime: this.formatDateTime(new Date()),
            updateTime: this.formatDateTime(new Date())
          };
          
          // 添加到列表
          this.itemrecptlineList.push(fakeData);
          this.total = this.itemrecptlineList.length;
          
          // 关闭弹窗
          this.open = false;
          
          // 静默处理，不显示假数据成功提示
          // this.$message.success('使用假数据模拟新增成功！');
          
          // 重置表单
          this.reset(); 
        } catch (error) {
          console.log('数据错误',error);
        }
      },
     
           // 测试数据功能（静默处理）
      testFakeData() {
        // 填充一些测试数据
        this.form.itemId = 'TEST_ITEM_' + Date.now();
        this.form.itemCode = 'TEST_CODE_' + Date.now();
        this.form.itemName = '测试物料';
        this.form.specification = '测试规格';
        this.form.unitOfMeasure = 'PCS';
        this.form.quantityRecived = 10;
        this.form.batchCode = 'TEST_BATCH_' + Date.now();
        this.form.expireDate = '2025-12-31';
        this.form.iqcCheck = 'N';
        this.form.remark = '这是测试假数据';
        
        // 设置测试仓库信息
        this.warehouseInfo = ['TEST_WH', 'TEST_LOC', 'TEST_AREA'];
        this.form.warehouseId = 'TEST_WH';
        this.form.locationId = 'TEST_LOC';
        this.form.areaId = 'TEST_AREA';
        this.form.warehouseName = '测试仓库';
        this.form.locationName = '测试库区';
        this.form.areaName = '测试库位';
        
        // 静默处理，不显示测试成功提示
        // this.$message.success('测试数据已填充，请点击确定按钮测试假数据功能');
      },
     handleFormPriceChange() {
       this.calculateTotalPrice(this.form);
     },
    // 调试方法：检查表单状态
    debugForm() {
      // 检查表单引用
      if (this.$refs.form) {
        // 手动验证表单
        this.$refs.form.validate((valid) => {
        });
      }
      // 显示用户友好的信息
      this.$message.info('调试信息已输出到控制台，请查看浏览器开发者工具');
    },
    //IQC检验单选择
    handleSelectIqc(){
      try {
        // 确保组件可见
        this.showItemSelect = true;
        // 等待组件渲染完成后再调用show方法
        this.$nextTick(() => {
          if (this.$refs.iqcSelect) {
            this.$refs.iqcSelect.show();
          } else {
            console.error('iqcSelect 引用不存在！');
            this.$message.error('检验单选择组件未正确加载，请刷新页面重试');
            // 尝试重新渲染组件
            this.forceRerenderIqcSelect();
          }
        });
      } catch (error) {
        console.error('检验单选择组件调用失败:', error);
        this.$message.error('检验单选择组件调用失败，请刷新页面重试');
      }
    },
    //IQC检验单选择弹出框
    onIqcSelected(obj){
      console.log(obj,this.currentRow,'选中');
      
        if(obj != undefined && obj != null){
          if (this.currentRow) {
            // 表格行中的检验单选择
            this.currentRow.iqcId = obj.iqcId;
            this.currentRow.iqcCode = obj.iqcCode;
            this.currentRow = null;
          } else {
            // 表单中的检验单选择
            this.form.iqcId = obj.iqcId;
            this.form.iqcCode = obj.iqcCode;
          }
          this.closeSelect();
        }
    },
    // 表格中检验单选择，
    handleTableIqcSelect(row){
      this.currentRow = row;
      try {
        // 确保组件可见
        this.showItemSelect = true;
        
        // 等待组件渲染完成后再调用show方法
        this.$nextTick(() => {
          if (this.$refs.iqcSelect) {
            this.$refs.iqcSelect.show();
          } else {
            console.error('iqcSelect 引用不存在！');
            this.$message.error('检验单选择组件未正确加载，请刷新页面重试');
            // 尝试重新渲染组件
            this.forceRerenderIqcSelect();
          }
        });
      } catch (error) {
        console.error('检验单选择组件调用失败:', error);
        this.$message.error('检验单选择组件调用失败，请刷新页面重试');
      }
    },
    closeSelect(){
      // 先关闭子组件的弹窗
      if (this.$refs.iqcSelect) {
        this.$refs.iqcSelect.showFlag = false;
      }
      // 使用 nextTick 确保DOM更新完成，避免闪烁
      this.$nextTick(() => {
        // 重置组件显示状态，但保持组件可见
        this.showItemSelect = true;
      });
    },
    // 测试检验单选择组件
    testIqcSelect() {
      this.handleSelectIqc(); // 调用检验单选择方法
    },
    addToLocalStorage(data) {
      console.log(data,'kkk')
      try {
        const existingData = this.getFromLocalStorage();
        // 为新增的数据生成临时ID，避免重复判断问题
        if (!data.tempId) {
          data.tempId = 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }
        const newData = [...existingData, data];
        localStorage.setItem(`itemrecptline_${this.recptId}`, JSON.stringify(newData));
        // 直接更新组件数据列表，确保立即显示
        this.$nextTick(()=>{
          this.itemrecptlineList = [...this.itemrecptlineList, data];
        })
        
        
        this.total = this.itemrecptlineList.length;
        console.log(this.itemrecptlineList,this.total,'this.itemrecptlineList')
        // 刷新列表显示合并后的数据
        this.refreshLocalList();
        // 如果新添加的数据不在当前页，跳转到最后一页
        if (this.total > this.queryParams.pageSize) {
          const lastPage = Math.ceil(this.total / this.queryParams.pageSize);
          if (this.queryParams.pageNum !== lastPage) {
            this.queryParams.pageNum = lastPage;
            this.$nextTick(() => {
              this.applyPagination();
            });
          }
        }
      } catch (error) {
        // 我在这里添加了调试失败的错误信息
        console.error('添加失败:', error);
      }
    },
    saveToLocalStorage(data) {
      try {
        const localData = data.filter(item => !item.lineId);
        localStorage.setItem(`itemrecptline_${this.recptId}`, JSON.stringify(localData));
        // 已保存的数据
        console.log('已保存数据:', localData);
      } catch (error) {
        console.error('保存数据失败:', error);
      }
    },
    getFromLocalStorage() {
      try {
        const data = localStorage.getItem(`itemrecptline_${this.recptId}`);
        if (!data) return [];
        const parsedData = JSON.parse(data);
        // 只返回有效的物料数据，过滤掉searchValue等无关对象
        return parsedData.filter(item => 
          item && 
          typeof item === 'object' && 
          item.itemCode && 
          item.itemName
        );
      } catch (error) {
        console.error('读取失败:', error);
        return [];
      }
    },
    refreshLocalList() {
      // 如果当前数据已经是最新的，不需要重新加载
      // 只需要重新应用分页即可
      this.applyPagination();
    },
    removeFromLocalStorage(row) {
      try {
        const existingData = this.getFromLocalStorage();
        let newData;
        
        if (Array.isArray(this.ids) && this.ids.length > 0) {
          // 批量删除：根据选中的ID数组删除
          newData = existingData.filter(item => !this.ids.includes(item.lineId));
        } else {
          // 单个删除：需要处理没有lineId的新数据
          if (row.lineId) {
            // 有lineId的数据，直接按ID删除
            newData = existingData.filter(item => item.lineId !== row.lineId);
          } else {
            // 没有lineId的新数据，需要按其他唯一标识符删除
            // 使用物料编码、批次号、仓库等字段组合来识别唯一性
            newData = existingData.filter(item => {
              return !(item.itemCode === row.itemCode && 
                      item.batchCode === row.batchCode && 
                      item.warehouseId === row.warehouseId &&
                      item.quantityRecived === row.quantityRecived);
            });
          }
        }
        // 更新
        localStorage.setItem(`itemrecptline_${this.recptId}`, JSON.stringify(newData));
        // 同时更新组件的数据列表
        this.itemrecptlineList = this.itemrecptlineList.filter(item => {
          if (row.lineId) {
            return item.lineId !== row.lineId;
          } else {
            return !(item.itemCode === row.itemCode && 
            item.batchCode === row.batchCode && 
            item.warehouseId === row.warehouseId &&
            item.quantityRecived === row.quantityRecived);
          }
        });
        // 更新总数
        this.total = this.itemrecptlineList.length;
        // 更新allData，确保分页数据也同步
        this.allData = this.allData.filter(item => {
          if (row.lineId) {
            return item.lineId !== row.lineId;
          } else {
            return !(item.itemCode === row.itemCode && 
                    item.batchCode === row.batchCode && 
                    item.warehouseId === row.warehouseId &&
                    item.quantityRecived === row.quantityRecived);
          }
        });
        // 重新应用分页
        this.applyPagination();
        if (this.itemrecptlineList.length === 0 && this.queryParams.pageNum > 1) {
          this.queryParams.pageNum--;
          this.$nextTick(() => {
            this.applyPagination();
          });
        }
        // 强制清理选择状态
        this.ids = [];
        this.single = true;
        this.multiple = true;
        // 如果当前正在编辑被删除的行，强制关闭弹窗
        if (this.open && this.form && 
            ((row.lineId && this.form.lineId === row.lineId) ||
             (!row.lineId && this.form.itemCode === row.itemCode))) {
          this.open = false;
          this.cleanFormState();
        }
      } catch (error) {
        console.error('删除数据失败:', error);
      }
    },
    clearLocalStorage() {
      try {
        localStorage.removeItem(`itemrecptline_${this.recptId}`);
        console.log('已清理数据');
      } catch (error) {
        console.error('清理失败:', error);
      }
    },
    exportLocalData() {
      try {
        if (this.itemrecptlineList && this.itemrecptlineList.length > 0) {
          const dataStr = JSON.stringify(this.itemrecptlineList, null, 2);
          const dataBlob = new Blob([dataStr], { type: 'application/json' });
          const url = URL.createObjectURL(dataBlob);
          const link = document.createElement('a');
          link.href = url;
          link.download = `itemrecptline_${this.recptId}_${new Date().toISOString().split('T')[0]}.json`;
          link.click();
          URL.revokeObjectURL(url);
          this.$message.success('数据导出成功');
        } else {
          this.$message.warning('没有数据可导出');
        }
      } catch (error) {
        console.error('导出数据失败:', error);
        this.$message.error('导出数据失败');
      }
    },
    async syncLocalDataToBackend() {
      try {
        const localData = this.getFromLocalStorage();
        if (!localData || localData.length === 0) {
          this.$message.warning('没有数据需要同步');
          return;
        }
        this.$modal.confirm('是否确认将数据同步到后端？这将覆盖后端现有数据。').then(async () => {
          this.loading = true;
          
          // 过滤出没有lineId的数据（新数据）
          const newData = localData.filter(item => !item.lineId);
          
          if (newData.length > 0) {
            // 批量添加新数据到后端
            const promises = newData.map(item => addItemrecptline(item));
            await Promise.all(promises);
          }
          
          // 过滤出有lineId的数据（已保存数据）
          const existingData = localData.filter(item => item.lineId);
          
          if (existingData.length > 0) {
            // 批量更新已存在的数据
            const promises = existingData.map(item => updateItemrecptline(item));
            await Promise.all(promises);
          }
          
          this.loading = false;
          this.$message.success('数据同步成功！');
          
          // 重新获取列表
          this.getList();
        });
      } catch (error) {
        console.error('同步数据到后端失败:', error);
        this.loading = false;
        this.$message.error('同步失败：' + (error.message || '未知错误'));
      }
    },
    
    // 前端分页方法
    applyPagination() {
      const startIndex = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const endIndex = startIndex + this.queryParams.pageSize;
      
      // 从所有数据中截取当前页的数据
      this.itemrecptlineList = this.allData.slice(startIndex, endIndex);
    },
    
    // 分页改变事件处理
    handlePaginationChange() {
      this.applyPagination();
      // 滚动到表格顶部
      this.$nextTick(() => {
        const tableEl = this.$el.querySelector('.el-table');
        if (tableEl) {
          tableEl.scrollIntoView({ behavior: 'smooth' });
        }
      });
    },
    // 强制重新渲染检验单选择组件
    forceRerenderIqcSelect() {
      console.log('强制重新渲染检验单选择组件');
      this.showItemSelect = false;
      this.$nextTick(() => {
        this.showItemSelect = true;
        this.$nextTick(() => {
          if (this.$refs.iqcSelect) {
            console.log('组件重新渲染成功，调用 show() 方法');
            this.$refs.iqcSelect.show();
          } else {
            console.error('组件重新渲染失败');
            this.$message.error('检验单选择组件加载失败，请检查网络连接或刷新页面');
          }
        });
      });
    },

    // 新增：清理表单状态的方法
    cleanFormState() {
      // 强制清理所有表单相关的状态
      this.form = {
        lineId: null,
        recptId: this.recptId,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantityRecived: 1,
        quantityOrder: null,
        batchCode: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        iqcCheck: 'N',
        iqcId: null,
        iqcCode: null,
        expireDate: null,
        unitPriceTaxIncl: 0,
        unitPriceTaxExcl: 0,
        discount: 1,
        taxRate: 0.13,
        totalPriceTaxIncl: 0,
        totalPriceTaxExcl: 0,
        remark: null,
        attr1: 'string',
        attr2: 'string',
        attr3: 'string',
        attr4: 'string',
        createBy: this.$store?.state?.user?.name || 'admin',
        createTime: this.formatDateTime(new Date()),
        updateBy: this.$store?.state?.user?.name || 'admin',
        updateTime: this.formatDateTime(new Date())
      };
      
      // 清理仓库选择状态
      this.warehouseInfo = [];
      
      // 重置表单验证状态
      if (this.$refs.form) {
        this.$refs.form.resetFields();
        this.$refs.form.clearValidate();
      }
      
      // 清理选择状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      
      // 强制更新组件
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    checkDataConsistency() {
      // 这原本就是来检查一个数据状态的方法里面原本只是一些输出信息
      console.log('');
    },

    // 新增：强制同步数据状态
    forceSyncDataState() {
      try {
        // 获取的最新数据
        const localData = this.getFromLocalStorage();
        
        // 同步到组件状态
        this.itemrecptlineList = [...localData];
        this.total = this.itemrecptlineList.length;
        
        // 重新应用分页
        this.applyPagination();
        
        // 强制更新组件
        this.$forceUpdate();
        console.log('数据状态已强制同步');
      } catch (error) {
        console.error('强制同步数据状态失败:', error);
      }
    },

    /**
     * 将后端数据追加到中
     * @param {Array} backendData - 后端传递的数据
     */
    appendBackendData(backendData) {
      if (!backendData || !Array.isArray(backendData)) {
        console.warn('数据添加失败');
        return;
      }

      try {
        // 获取当前数据
        const currentLocalData = this.getFromLocalStorage();
        console.log('当前数据:', currentLocalData);
        console.log('要追加的后端数据:', backendData);

        // 合并数据，避免重复
        const combinedData = [...backendData];
        
        currentLocalData.forEach(localItem => {
          // 只添加没有lineId的数据,把他添加进去
          if (!localItem.lineId) {
            const isDuplicate = backendData.some(backendItem => 
              backendItem.itemCode === localItem.itemCode
            );
            
            if (!isDuplicate) {
              combinedData.push(localItem);
            }
          }
        });
        // 保存合并后的数据
        localStorage.setItem(`itemrecptline_${this.recptId}`, JSON.stringify(combinedData));
        // console.log('后端数据已追加到:', combinedData);

        // 先设置allData，再应用分页
        this.allData = combinedData;
        this.total = combinedData.length;
        // 重置分页到第一页
        this.queryParams.pageNum = 1;
       // 应用分页
        this.applyPagination();
        
        // 计算总价
        this.calculateMainTotalPrice();

      } catch (error) {
        console.error('追加后端数据到失败:', error);
      }
    },

    /**
     * 根据我们的渲染条件来去渲染我们的数据
     */
    renderFromLocalCache() {
      try {
        const localData = this.getFromLocalStorage();
        console.log('从渲染数据:', localData);
        
        if (localData && localData.length > 0) {
          this.allData = localData;
          this.total = localData.length;
          
          // 重置分页到第一页
          this.queryParams.pageNum = 1;
          
          // 应用分页
          this.applyPagination();
          
          // 计算总价
          this.calculateMainTotalPrice();
        } else {
          console.log('无数据，这个时候我们将清空列表');
          this.allData = [];
          this.total = 0;
          this.itemrecptlineList = [];
        }
      } catch (error) {
        console.error('从渲染数据失败:', error);
      }
    },

    /**
     * 处理外部传入的后端数据
     * @param {Array} externalData - 外部传入的后端数据
     * @param {boolean} forceRefresh - 是否强制刷新，默认false
     */
    handleExternalBackendData(externalData, forceRefresh = false) {
      if (!externalData || !Array.isArray(externalData)) {
        console.warn('外部传入的数据无效');
        return;
      }

      console.log('处理外部传入的后端数据:', externalData);
      console.log('强制刷新标志:', forceRefresh);

      if (forceRefresh) {
        // 强制刷新：清空，只使用外部数据
        this.clearLocalCache();
        // 直接更新组件数据
        this.updateFromComputedData();
      } else {
        // 正常追加：将外部数据追加到现有
        this.appendBackendData(externalData);
      }
    },

    /**
     * 清空
     */
    clearLocalCache() {
      try {
        localStorage.removeItem(`itemrecptline_${this.recptId}`);
        console.log('已清空');
      } catch (error) {
        console.error('清空失败:', error);
      }
    },

    /**
     * 从计算属性更新组件数据
     */
    updateFromComputedData() {
      try {
        const mergedData = this.computedMergedData;
        console.log('从计算属性更新数据:', mergedData);
        
        this.allData = mergedData;
        this.total = mergedData.length;
        // 直接显示所有数据，不分页
        this.itemrecptlineList = [...mergedData];
        
        // 计算总价
        this.calculateMainTotalPrice();
        
      } catch (error) {
        console.error('从计算属性更新数据失败:', error);
      }
    },

    // 日期格式化方法
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 日期时间格式化方法
    formatDateTime(date) {
      if (!date || !(date instanceof Date)) {
        date = new Date();
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 验证并修正日期时间格式
    validateAndFixDateTime(dateString, fieldName) {
      if (!dateString || typeof dateString !== 'string') {
        return this.formatDateTime(new Date());
      }
      
      // 检查是否已经是正确的格式 yyyy-MM-dd HH:mm:ss
      if (dateString.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
        return dateString;
      }
      
      // 检查是否是 yyyy-MM-dd HH:mm 格式，缺少秒数
      if (dateString.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/)) {
        const fixedDate = dateString + ':00';
        console.log(`修正 ${fieldName} 格式从 "${dateString}" 到 "${fixedDate}"`);
        return fixedDate;
      }
      
      // 检查是否是 yyyy-MM-dd 格式，缺少时间
      if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
        const fixedDate = dateString + ' 00:00:00';
        console.log(`修正 ${fieldName} 格式从 "${dateString}" 到 "${fixedDate}"`);
        return fixedDate;
      }
      
      // 如果格式不正确，返回当前时间
      console.warn(`日期格式不正确 "${dateString}"，使用当前时间`);
      return this.formatDateTime(new Date());
    }
  }
};
</script>
